﻿#coding:utf-8
import urllib2
import cookielib
import urllib
import re
import sys
from BeautifulSoup import BeautifulSoup

#使用前先安装用python工具pip安装模块
# BeautifulSoup 在线帮助文档
# http://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/


#解决中文报错问题
reload(sys)
sys.setdefaultencoding("utf8")

#####################################
openUrl = 'http://www.zhihu.com/#signin'
loginUrl = 'http://www.zhihu.com/login/phone_num'


# 将cookies绑定到一个opener,cookie由cookielib自动管理
cookie = cookielib.CookieJar()
handler = urllib2.HTTPCookieProcessor(cookie)
opener = urllib2.build_opener(handler)

#设置请求头信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
    'Connection': 'keep-alive'
}

#请求参数
data = {
    'account': 'phone',
    'password': 'pwd',
    'remember_me': 'true'
}

try:
    # 构造request请求
    request = urllib2.Request(openUrl,headers=headers)
    
    # 接收返回的数据
    response = urllib2.urlopen(request)
    loginPage = response.read()
    
    #读取页面的name:  _xsrf  -- value:  b3bec39ebc84685244ff7288d000cb2c
    soup = BeautifulSoup(loginPage)
    input = soup.input
    #print 'name:',input['name'],' -- value:',input['value']
    data[input['name']] = input['value']
    
    # 构造request请求，对参数编码
    encodedata = urllib.urlencode(data)
    print encodedata
    request = urllib2.Request(loginUrl, encodedata, headers=headers)
    # 接收返回的数据
    response = urllib2.urlopen(request)
    loginPage = response.read()
    
    print loginPage
except Exception, e:
    print e














